package cn.fancy.sdk.pay.ali;

import static cn.fancy.sdk.utils.SpMmkvUtils.KEY_VERTICAL_ORIENTATION;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;
import cn.fancy.sdk.common.utils.ResUtil;
import cn.fancy.sdk.pay.entity.PaymentId;
import cn.fancy.sdk.pay.view.RoundWebView;
import cn.fancy.sdk.utils.DensityUtil;
import cn.fancy.sdk.utils.SpMmkvUtils;
import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;

public class AlipayH5Activity extends Activity {
    private static final String TAG = AlipayH5Activity.class.getSimpleName();
    
    private RoundWebView aliWebView;
    private int paymentId;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(screenVertical()){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            Log.w(TAG, TAG + "setRequestedOrientation PORTRAIT");
        }
        
        setContentView(ResUtil.getLayoutId(getBaseContext(), "guild_alipayactivity"));
        
        String url = getIntent().getStringExtra("url");
        int paytype = getIntent().getIntExtra("paytype", 0);
        paymentId = getIntent().getIntExtra("paymentId", 0);
    
        aliWebView = (RoundWebView) this.findViewById(ResUtil.getId(this, "aliwebview"));

        if (scanPayType()) {
            initScanView();
        }
        
        Log.d(TAG, TAG + "open" + url);
    
        WebSettings settings = aliWebView.getSettings();
        settings.setRenderPriority(RenderPriority.HIGH);
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setMinimumFontSize(settings.getMinimumFontSize() + 8);
        settings.setAllowFileAccess(false);
        aliWebView.setVerticalScrollbarOverlay(true);
        
        if (paytype == 2) {
            aliWebView.setWebViewClient(new MyWebViewClient());
        }
        aliWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
        aliWebView.loadUrl(url);
    }
    
    private boolean scanPayType() {
        int payment = getIntent().getIntExtra("paymentId", 0);
        return payment == PaymentId.ALIPAY_SCAN_CODE || payment == PaymentId.WEIXIN_SCAN_CODE;
    }
    
    private void initScanView() {
        ImageView rlTopBar = (ImageView) this.findViewById(ResUtil.getId(this, "guild_pay_back"));
        rlTopBar.setVisibility(View.VISIBLE);
    
        ImageView guild_pay_back = (ImageView) this.findViewById(ResUtil.getId(this, "guild_pay_back"));
        guild_pay_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelPayFinish();
            }
        });
    
        RelativeLayout rl = (RelativeLayout) this.findViewById(ResUtil.getId(this, "rl"));
        rl.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        rl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                cancelPayFinish();
            }
        });
    
        double screenWidth = DensityUtil.getScreenWidth(this);
        double screenHeight = DensityUtil.getScreenHeight(this);
        double minVal = Math.min(screenWidth, screenHeight);
        minVal = DensityUtil.dip2px(this, 400);
        RelativeLayout.LayoutParams layoutParams = (LayoutParams) aliWebView.getLayoutParams();
        layoutParams.width = 1040;
        layoutParams.height = 1000;
        layoutParams.topMargin = 6;
        layoutParams.bottomMargin = 6;
        
        aliWebView.setLayoutParams(layoutParams);
        aliWebView.setRadius(DensityUtil.dip2px(this, 12));
        
        Log.d(TAG, "aliWebView minval:" + minVal);
//        Toast.makeText(this, "minVal:"+minVal,Toast.LENGTH_SHORT).show();
    }
    
    private boolean screenVertical() {
        return SpMmkvUtils.getValue(this, KEY_VERTICAL_ORIENTATION)
            .equals(KEY_VERTICAL_ORIENTATION);
    }
    
    private class MyWebViewClient extends WebViewClient {
        
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            Log.d(TAG, TAG + "shouldOverrideUrlLoading");
            if (!(url.startsWith("http") || url.startsWith("https"))) {
                return true;
            }
            
            if (paymentId == PaymentId.ALIPAY_ID) {
                // 推荐采用的新的二合一接口(payInterceptorWithUrl),只需调用一次
                final PayTask task = new PayTask(AlipayH5Activity.this);
                Log.d("Taskverion", "Taskverion" + task.getVersion());
                boolean isIntercepted = task.payInterceptorWithUrl(url, true, new H5PayCallback() {
                    // 支付结果返回
                    @Override
                    public void onPayResult(final H5PayResultModel result) {
                        Log.d("AlipayH5rst", "AlipayH5rst" + result.getResultCode() + "," + result.getReturnUrl());
                        final String url = result.getReturnUrl();
                        if (!TextUtils.isEmpty(url)) {
                            AlipayH5Activity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    view.loadUrl(url);
                                    Log.d(TAG, TAG + "notload");
                                }
                            });
                        }
                        AlipayH5Activity.this.finish();
                    }
                });
        
                //判断是否成功拦截 若成功拦截，则无需继续加载该URL；否则继续加载
                if (!isIntercepted) {
                    Log.d(TAG, TAG + "notisIntercepted");
                    view.loadUrl(url);
                }
            }
            return true;
        }
    
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            aliWebView.loadUrl("javascript:function finishActivity(){JSInterface.finishActivity();}");
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (aliWebView != null) {
            aliWebView.removeAllViews();
            try {
                aliWebView.destroy();
            } catch (Throwable t) {
                t.printStackTrace();
            }
            aliWebView = null;
        }
    }
    
    public class JSInterface{
        @android.webkit.JavascriptInterface
        public void finishActivity(){
            cancelPayFinish();
        }
    }
    
    private void cancelPayFinish() {
        Intent intent = new Intent();
        intent.putExtra(AlipayView.REQ_EXTRA_MONEY, getIntent().getStringExtra("money"));
        setResult(RESULT_OK, intent);
        AlipayH5Activity.this.finish();
    }
    
}
